import { notify } from '@/utils/element'

interface Params {
  initData?: any; // 初始数据（一般用于新增时的初始数据）
  add?: Function;
  update?: Function;
  getMenuSelect?: Function; // 获取系统菜单级联下拉选择框
  getDeptSelect?: Function; // 获取部门管理下拉选择框
}

function useForm<T>(params: Params, emit?: any, _props?: any) {
  const { initData = {}, add = () => { }, update = () => { } } = params;

  // 表单ref
  const formRef = ref()
  // 定义状态
  const state = reactive({
    visible: false,
    loading: false,
    selectLoading: false,
    title: '新增',
    type: 'add' as FormType,
    pageTypes: {
      page: 1, // 当前页码
      size: 10, // 每页显示多少条
      total: 0, // 总记录数
    } as PageType,
    menuList: [],
    deptsOptions: [],
    formData: {} as T,
    oldFormData: {} as T
  });

  /**
   * 打开窗口
   */
  function open(type: FormType, title: string, data = {} as any) {
    state.type = type;
    state.title = title;
    // 合并数据并深度拷贝对象
    state.formData = JSON.parse(JSON.stringify({ ...initData, ...data }));
    console.log('打开窗口', state.formData);

    // 当修改操作时，做数据校验需要使用
    state.oldFormData = Object.assign({}, state.formData);
    state.visible = true;

    // 查询系统菜单项
    loadMenuSelect()

    // 获取部门管理树形结构
    loadDeptSelect()
  }

  // 关闭窗口
  function close() {
    if (state.loading) return;
    //清空表单，清除校验提示
    formRef.value?.resetFields();
    state.visible = false;
  }

  // 提交表单
  function submitForm() {
    formRef.value?.validate((valid: boolean) => {
      if (!valid) return;
      submitData();
    });
  }

  // 提交数据
  async function submitData() {
    try {
      console.log('提交数据', state.formData)
      state.loading = true;
      let res;
      if (state.type === 'edit') {
        // 修改
        res = await update(state.formData);
      } else {
        // 新增
        res = await add(state.formData);
      }

      state.loading = false;// 防止close关闭不了窗口
      if (res.code !== 200) return;
      notify('操作成功！', { type: 'success' });
      // 关闭窗口
      close();
      // 触发事件让父组件刷新列表
      emit('refresh');
    } catch (e) {
    } finally {
      state.loading = false;
    }
  }

  // 查询所有菜单(不加载按钮)
  async function loadMenuSelect() {
    try {
      if (params.getMenuSelect) {
        const { data } = await params.getMenuSelect()
        console.log('查询所有菜单', data);
        state.menuList = data.results;
      }
    } catch (error) {
    } finally {
    }
  }

  // 获取部门管理树形结构
  async function loadDeptSelect() {
    try {
      if (params.getDeptSelect) {
        const { data } = await params.getDeptSelect()
        console.log('获取部门管理树形结构', data);
        state.deptsOptions = data.results;
      }
    } catch (error) {
    } finally {
    }
  }

  return {
    formRef,
    ...toRefs(state),
    open,
    close,
    submitForm,
  }
}

export default useForm;
export { useForm };